package com.myfojing.mycloud;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;


public class RegisterActivity extends AppCompatActivity {

    private final String LOGTAG = "调试mdns";
    private final String[] modes = {"空模式", "站点", "访问点", "基站"};
    WifiManager.MulticastLock multicastLock;

    TextInputEditText discover_title;
    TextInputEditText discover_desc;
    TextInputEditText discover_ip;
    TextInputEditText discover_port;
    TextInputEditText discover_type;

    ListView listView;
    Handler handler;

    DiscoveryListviewAdapter adapter;
    private String serviceType = "_nodemcu._tcp.local.";
    private JmDNS jmdns;
    private ServiceListener listener;
    private ServiceInfo serviceInfo;
    private int mPosition = 0;
    // 扫描结果
    private ArrayList<Sensirion> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discovery);

        // my code
        // ui
//        discover_title = (TextInputEditText) findViewById(R.id.discover_title);
//        discover_desc = (TextInputEditText) findViewById(R.id.discover_desc);
//        discover_ip = (TextInputEditText) findViewById(R.id.discover_ip);
//        discover_port = (TextInputEditText) findViewById(R.id.discover_port);
//        discover_type = (TextInputEditText) findViewById(R.id.discover_type);

        listView = (ListView) findViewById(R.id.lvScanResult);
        listView.addHeaderView(getLayoutInflater().inflate(R.layout.discovery_listview_header,
                null, false));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                mPosition = position;
                //
                HashMap<String, String> tmp = (HashMap<String, String>) listView.getItemAtPosition(position);
                discover_title.setText(tmp.get("name"));
                discover_ip.setText(tmp.get("ip"));
                discover_port.setText(tmp.get("port"));
            }
        });

        handler = new Handler();

        list = new ArrayList<>();
        adapter = new DiscoveryListviewAdapter(this, list);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        multicastLock.release();
        try {
            jmdns.unregisterAllServices();
            jmdns.close();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }

        jmdns = null;
    }

    /*  用户定义函数 */
    // 扫描按钮
    public void onScanClick(View view) {
        jmdns();
    }

    // 配置按钮
    public void onConfigClick(View view) {
/*        Intent intent = new Intent(this, ConfigWifiActivity.class);
        // listview 选中
        HashMap<String, String> tmp = (HashMap<String, String>) listView.getItemAtPosition(mPosition);
        intent.putExtra("ip", tmp.get("ip"));
        intent.putExtra("port", tmp.get("port"));
        intent.putExtra("mac", tmp.get("mac"));
        startActivity(intent);*/
    }

    // 保存按钮
    public void onSaveClick(View view) {
        Sensirion tmp = (Sensirion) listView.getItemAtPosition(mPosition);
        //SensirionHelper.save_or_update(tmp);
    }

    // 获得IP
    private InetAddress getLocalIpAddress() {
        WifiManager wifiManager = (WifiManager) getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        InetAddress address = null;
        try {
            address = InetAddress.getByName(String.format(Locale.ENGLISH,
                    "%d.%d.%d.%d", (ipAddress & 0xff),
                    (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address;
    }

    private void jmdns() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WifiManager wifiManager = (WifiManager) getApplicationContext()
                        .getSystemService(Context.WIFI_SERVICE);
                multicastLock = wifiManager.createMulticastLock(getClass().getName());
                multicastLock.setReferenceCounted(false);
                try {
                    final InetAddress inetAddress = getLocalIpAddress();
                    multicastLock.acquire();
                    jmdns = JmDNS.create(inetAddress, "Observer");
                    listener = new ServiceListener() {
                        @Override
                        public void serviceAdded(ServiceEvent event) {
                            jmdns.requestServiceInfo(event.getType(),
                                    event.getName(), 1000);
                        }

                        @Override
                        public void serviceRemoved(ServiceEvent event) {
                            Log.e(LOGTAG, "服务移除: " + event.getName());
                        }

                        @Override
                        public void serviceResolved(ServiceEvent event) {
                            Log.e(LOGTAG, "服务分析: " + event.getInfo().getQualifiedName() + " port:" + event.getInfo().getPort());
                            //Log.e(LOGTAG, "服务类型 : " + event.getInfo().getType());
                            serviceInfo = event.getInfo();

                            // 数据
                            String name = serviceInfo.getName();
                            // 是否已经存在
                            Sensirion model = new Sensirion();
                            InetAddress inetAddress_1 = serviceInfo.getInet4Addresses()[0];
                            String ip = inetAddress_1.getHostAddress();
                            String mac = serviceInfo.getPropertyString("mac");
                            String mode = modes[Integer.parseInt(serviceInfo.getPropertyString("mode"))];

                            model.setTitle(name);
                            model.setIp(ip);
                            model.setPort(Integer.toString(serviceInfo.getPort()));
                            //model.put("mode", mode);
                            model.setMac(mac);
                            //list.clear();
                            list.add(model);
                            // 刷新
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }
                    };

                    jmdns.addServiceListener(serviceType, listener);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // end
}


